var API = (function() {

const BASE_URL = 'https://study.duyiedu.com';
const TOKEN_KEY = 'token';

function get(path){
    let headers = {};
    const token = localStorage.getItem(TOKEN_KEY);
    if(token){headers.authorization = `Bearer ${token}`}
    return fetch(BASE_URL + path,{headers});
}

function post(path,bodyObj){
    const headers = {
        'Content-Type': 'application/json',
    };
    const token = localStorage.getItem(TOKEN_KEY);
    if(token){headers.authorization = `Bearer ${token}`}
    return fetch(BASE_URL + path,{headers,method:'POST',body:JSON.stringify(bodyObj)});
}

async function reg(userInfo){
    return await (await post('/api/user/reg',userInfo)).json();
}

async function login(loginInfo){
    const resp = await post('/api/user/login',loginInfo);
    const result = await resp.json();
    if(result.code === 0){
        const token = resp.headers.get('authorization');
        localStorage.setItem(TOKEN_KEY, token);
    }
    return result;
}

async function exists(loginId){
    return await (await get('/api/user/exists?loginId='+loginId)).json();
}

async function profile(){
  return await (await get('/api/user/profile')).json(); 
}

async function sendChat(content){
    return await (await post('/api/chat',{
        content:content,
    })).json();
}

async function getHistory(){
    return await (await get('/api/chat/history')).json();
}

function loginOut(){
    localStorage.removeItem(TOKEN_KEY);
}

return {
    reg,
    login,
    exists,
    profile,
    sendChat,
    getHistory,
    loginOut,
}
})();